package org.yu.team2023.flashdays.item;

import net.minecraft.ChatFormatting;
import net.minecraft.nbt.NbtUtils;
import net.minecraft.network.chat.Component;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResultHolder;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.TooltipFlag;
import net.minecraft.world.level.Level;
import org.apache.commons.lang3.RandomUtils;
import org.jetbrains.annotations.Nullable;
import org.yu.team2023.flashdays.ModUtil;
import org.yu.team2023.flashdays.TreasureQuality;
import org.yu.team2023.flashdays.TreasureSets;

import java.util.Arrays;
import java.util.List;

public class TreasureBox extends Item {
    protected final String key;
    public TreasureBox(Properties pProperties,String key) {
        super(pProperties);
        this.key=key;
    }

    @Override
    public InteractionResultHolder<ItemStack> use(Level pLevel, Player pPlayer, InteractionHand pUsedHand) {
        if(!TreasureSets.TREASURE_SETS_MAP.containsKey(key))return InteractionResultHolder.fail(pPlayer.getItemInHand(pUsedHand));
            var box=pPlayer.getItemInHand(pUsedHand);
        for (int i = 0; i < 3; i++) {
           var item= ModUtil.randomSelect(TreasureSets.TREASURE_SETS_MAP.get(key).getCuriosList()).get();
           var stack= TreasureCurios.newInstance(item,isGreat(box)?TreasureQuality.EPIC:ModUtil.randomSelect(Arrays.stream(TreasureQuality.values()).toList()),item.getIndex() );
           pPlayer.addItem(stack);
        }
        if(!pPlayer.getAbilities().instabuild)
            pPlayer.getItemInHand(pUsedHand).shrink(1);
        return super.use(pLevel, pPlayer, pUsedHand);
    }
    public ItemStack createGreat(){
        ItemStack stack=new ItemStack(this);
        stack.getOrCreateTag().putBoolean("isGreat",true);
        return stack;
    }
    @Override
    public void appendHoverText(ItemStack pStack, @Nullable Level pLevel, List<Component> pTooltipComponents, TooltipFlag pIsAdvanced) {
        super.appendHoverText(pStack, pLevel, pTooltipComponents, pIsAdvanced);
        pTooltipComponents.add(Component.translatable("tip.treasure_box",Component.translatable("tip."+this.key+".nameDesc")));
        if(isGreat(pStack))pTooltipComponents.add(Component.translatable("tip.box.great").withStyle(ChatFormatting.GOLD));
    }
    protected boolean isGreat(ItemStack stack){
        return stack.hasTag() && stack.getOrCreateTag().getBoolean("isGreat");
    }

}
